<?php

class CSVDataParser extends DataParser {

    public function parseData($data) {

        $str = str_replace("\"\n", "\"\r", $data);
        $arr = str_getcsv($str, "\r", "'"); // 5.3.3 Bug?
        $fields = str_getcsv($arr[0]);
        $keyword = $this->getOption('keywords');
        $keywords = explode(",", $keyword);
        $direction = $this->getOption('direction');
        foreach ($arr as $i => $msg) {
            if ($i != 0) {
                $arrs = str_getcsv($msg);
                foreach ($fields as $j => $field) {
                    $detail[$field] =  $arrs[$j];
                }
                if (isset($keyword) && isset($detail['ORG_NAME']) && isset($direction)) {
                    if ($direction == 0) {
                        foreach ($keywords as $key) {
                            if (!strpos($detail['ORG_NAME'], $key)) {
                                $array[] = $detail;
                            }
                        }
                    } else if ($direction == 1) {
                        foreach ($keywords as $key) {
                            if (strpos($detail['ORG_NAME'], $key)) {
                                $array[] = $detail;
                            }
                        }
                    }
                } else {
                    $array[] = $detail;
                }
            }
        }
        $this->setTotalItems(count($array));
        return $array;
    }
}
